/**
 * 微信公众号使用
 */
const robot = require('../service/robot'); 
const Wechat = require('../service/wechat');
const robotConfig = require('../config/baidu');
const wechatConfig = require('../config/weixin');
const sessonIdMap = {}; //存放session

 /**
  * 请求入口
  */
 exports.route = (req, res) => {
    const wechat = Wechat(wechatConfig.token);
    //检验 token
    wechat.checkSignature(req, res);
    //预处理
    wechat.handler(req, res);
    //监听文本信息
    wechat.text(data => {

        console.log(`微信数据包信息：${JSON.stringify(data)}`);
        const {
            'ToUserName' : fromUser, 
            'FromUserName' : toUser,
            'Content': content
        } = data;

        let msg = {
            'FromUserName' : fromUser,
            'ToUserName' : toUser,
            //'MsgType' : "text",
            'Content' : "我走神啦，麻烦再说一遍啦~~~"
        }

        const {SERVICE_ID, BOT_IDS} = robotConfig;
        console.info(`SERVICE_ID: ${SERVICE_ID}, BOT_IDS: ${BOT_IDS}`)
        robot.chatToRobot({ //调用机器人接口
            message : content , 
            sessonId : sessonIdMap[toUser] || null, 
            serviceId : SERVICE_ID,
            skillIds : BOT_IDS,
            userId : toUser
        }).then(json => {
            //回复信息
            console.info(`机器人回包信息:${JSON.stringify(json)}`);
            const {data ,result} = json;
            if(result == 0 && data['error_code'] == 0) {
                const {'result' : robotData} = data; 
                const {'session_id' : botSessionId} = robotData;
                const {'response_list' : responseList} = robotData;
                const {'action_list' : actionList} = responseList && responseList[0] || {};

                sessonIdMap[toUser] = botSessionId; //建立会话的sessionid
                
                if(actionList && actionList.length) {
                    const aciton = actionList[Math.floor(Math.random() * actionList.length)];
                    msg['Content'] = aciton.say;
                }
                  
            }
            wechat.send(msg);
        }).catch(e => {
            //回复信息
            wechat.send(msg);
        });
    });
    
}